<template>
  <div class="AppointmentAddGood">
    <c-title :hide="false" :text="title"></c-title>
    <van-tabs v-model="active">
      <van-tab title="商品套餐" name="1"></van-tab>
      <van-tab title="关联项目" name="2"></van-tab>
    </van-tabs>
    <div class="goodsBox" v-if="active == 1">
      <cellGroup :required="true" :label="'商品名称'" :inpval.sync="goods.title" :contenType="'inp'" :placeholderTxt="'请输入商品名称'"></cellGroup>
      <cellGroup :required="true" :label="'商品单位'" :inpval.sync="goods.sku" :contenType="'inp'" :placeholderTxt="'请输入商品单位'"></cellGroup>
      <cellGroup :required="true" :partition="true" :label="'商品分类'" :contenType="'link'" @tapLink="showCategoryPop" :linkConten="选择商品分类"></cellGroup>
      <div class="boxCell">
        <div class="cellS">
          <div v-for="(tag, index) in goodsCategory" :key="index" class="category-tag" @click="showCategoryPop(tag, index)">
            <div style="background-color: #f3f3f3; padding: 0.2rem 0.5rem;">
              <span v-if="tag.parent_name">{{ tag.parent_name }}</span>
              <span v-if="tag.child_name">/{{ tag.child_name }}</span>
              <span v-if="tag.third_name">/{{ tag.third_name }}</span>
            </div>
            <span class="close-icon" @click.stop="removeCategory(index)">x</span>
          </div>
        </div>
      </div>
      <cellGroup :required="true" :partition="true" :label="'商品图片'" :contenType="'uploadimg'" @uploadImg="imgUpload($event, 'thumb')" :linkConten="goods.thumb"></cellGroup>
      <cellGroup :label="'其他图片'" :contenType="'uploadimgMore'" @del="thumbUrlDel" @uploadImg="imgUpload($event, 'thumb_url')" :linkConten="goods.thumb_url"></cellGroup>
      <cellGroup :partition="true" v-if="!goodsId" :label="'商品详情'" :contenType="'link'" @tapLink="showGoodsDetailPop" :linkConten="goods.content ? '修改' : '请添加'"></cellGroup>
      <cellGroup :required="true" :partition="true" :label="'商品现价'" :inpval.sync="goods.price" :contenType="'inp'" :placeholderTxt="'请输入商品现价'"></cellGroup>
      <cellGroup :label="'商品原价'" :contenType="'inp'" :inpval.sync="goods.market_price" :placeholderTxt="'请输入商品原价'"></cellGroup>
      <cellGroup :label="'商品成本'" :contenType="'inp'" :inpval.sync="goods.cost_price" :placeholderTxt="'请输入商品成本'"></cellGroup>
      <cellGroup :required="true" :label="'商品库存'" :contenType="'inp'" :inpval.sync="goods.stock" :placeholderTxt="'请输入商品库存'"></cellGroup>
      <cellGroup :label="'减库存方式'" :contenType="'link'" @tapLink="showStockTypePop" :linkConten="stockTypeText"></cellGroup>
      <cellGroup :label="'不可退货退款'" :partition="true" :contenType="'switch'" :checkedPost="goods.no_refund" @switchTap="switchTap"></cellGroup>
      <cellGroup :label="'商品编码'" :contenType="'inp'" :inpval.sync="goods.goods_sn" :placeholderTxt="'请输入商品编码'"></cellGroup>
      <cellGroup :label="'商品条码'" :contenType="'inp'" :inpval.sync="goods.product_sn" :placeholderTxt="'请输入商品条码'"></cellGroup>
    </div>
    <div class="porject" v-if="active == 2">
      <div class="projectTemplate" v-for="(item, index) in widgets.appointment_project" :key="index">
        <div class="projectTemplate_t">
          <div class="name">项目{{ index + 1 }}</div>
          <div class="del" @click="delProject(index)">删除</div>
        </div>
        <cellGroup
          :required="true"
          :label="'选择项目'"
          :blackC_is="projectCheck(item, index) != '请选择' ? true : false"
          :contenType="'link'"
          :linkConten="projectCheck(item, index)"
          @tapLink="showSearchProjectOpen($event, index)"
        ></cellGroup>
        <cellGroup :required="true" :label="'预约次数'" :inpval.sync="item.service_count" :contenType="'inp'" :placeholderTxt="请输入预约次数"></cellGroup>
        <!-- <cellGroup :label="'门店分润（元）'" :inpval.sync="item.price" :contenType="'inp'" :placeholderTxt="请输入门店分润金额"></cellGroup>
        <cellGroup :label="'技师分润（元）'" :inpval.sync="item.worker_commission" :contenType="'inp'" :placeholderTxt="请输入技师分润金额"></cellGroup>
        <cellGroup :label="'招商员分润（元）'" :inpval.sync="item.merchant_staff_commission" :contenType="'inp'" :placeholderTxt="请输入招商员分润金额"></cellGroup>
        <cellGroup :label="'区域代理分红'" :inpval.sync="item.area_set" :contenType="'switch'" :checkedPost="item.area_set" @switchTap="areaSwitchTap($event, index)"></cellGroup> -->
        <template v-if="item.area_set">
          <cellGroup :label="'省（元）'" :contenType="'inp'" :inpval.sync="item.province" :placeholderTxt="请输入金额"></cellGroup>
          <cellGroup :label="'市（元）'" :contenType="'inp'" :inpval.sync="item.city" :placeholderTxt="请输入金额"></cellGroup>
          <cellGroup :label="'区/县（元）'" :contenType="'inp'" :inpval.sync="item.district" :placeholderTxt="请输入金额"></cellGroup>
          <cellGroup :label="'乡镇/街道（元）'" :contenType="'inp'" :inpval.sync="item.street" :placeholderTxt="请输入金额"></cellGroup>
        </template>
      </div>
      <div class="addProject" @click="addProjectMethod"><van-icon name="plus" />添加项目</div>
    </div>

    <div class="subBox">
      <div class="subBtn" @click="submitTap">确认发布</div>
    </div>
    <!-- 商品详情 -->
    <goods-detail-popup ref="detailPopup" :defaultType="goods.content" @saveDetail="saveGoodsDetail"></goods-detail-popup>
    <!-- 选择分类 -->
    <goods-category-popup ref="categoryPopup" v-if="categoryMenus.length > 0" :categoryList="categoryMenus" @confirmType="editCategory"></goods-category-popup>
    <!-- 库存 -->
    <stock-type-popup ref="stockPopup" :defaultType="goods.reduce_stock_method" @confirmType="editStockType"></stock-type-popup>
    <!-- 选择项目 -->
    <van-popup v-model="showSearchProject" :style="{ height: '31rem' }" round position="bottom">
      <van-nav-bar title="选择项目" @click-left="onClickLeft" @click-right="onClickRight">
        <template #right>
          <span>确定</span>
        </template>
        <template #left>
          <span>返回</span>
        </template>
      </van-nav-bar>
      <div class="searchBox">
        <van-search v-model="keyword" placeholder="请输入搜索关键词" @search="on_search" />
        <van-radio-group v-model="radio">
          <div class="cell" :key="index" v-for="(item, index) in projectList" @click="tapTouch(item.id)">
            <div class="cell_l">{{ item.title }}</div>
            <div class="cell_r">
              <van-radio :name="item.id" />
            </div>
          </div>
          <van-empty image="search" description="暂无更多" v-if="projectList.length <= 0" />
        </van-radio-group>
      </div>
    </van-popup>
  </div>
</template>
<script>
import goodsDetailPopup from "../../store_management/components/baseInfo_popups/goods_detail_pop";
import goodsCategoryPopup from "../../store_management/components/baseInfo_popups/goods_category_pop";
import stockTypePopup from "../../store_management/components/baseInfo_popups/stock_type_pop";
import cellGroup from "../components/addGoodCell.vue";
export default {
  data() {
    return {
      keyword: "",
      radio: "",
      active: "1",
      getJson: {},
      getDatUrl: "",
      title: "",
      categoryMenus: [],
      addCategoryIndex: "",
      projectArray: [],
      showSearchProject: false,
      showSearchProject_index: null,
      goodsCategory: [],
      goods: {
        title: "",
        category: [],
        sku: "",
        stock: "",
        thumb: "",
        thumb_url: [],
        content: "",
        market_price: [],
        price: "",
        cost_price: "",
        no_refund: false,
        goods_sn: "",
        product_sn: "",
        reduce_stock_method: 0
      },
      widgets: {
        appointment_project: []
      },
      goodsId: null,
      page: 1,
      projectList: [],
      total_page: 0
    };
  },
  activated() {
    this.goodsId = this.$route.params.id;
    this.AppointmentAddGood = false;
    if (this.fun.isTextEmpty(this.goodsId)) {
      this.title = "商品发布";
    } else {
      this.title = "商品编辑";
      this.getJson = { goods_id: this.$route.params.id };
      this.getDatUrl = "plugin.appointment.frontend.project-goods.goods-detail";
      this.getGoodsDetail();
    }
    this.getClass();
  },
  computed: {
    projectCheck(item) {
      return function(item) {
        let str = "请选择";
        if (this.projectList.length <= 0) return str;
        if (item.project_id) {
          for (let i = 0; i < this.projectList.length; i++) {
            if (this.projectList[i].id == item.project_id) {
              return this.projectList[i].title;
            }
          }
        }
        return str;
      };
    },
    stockTypeText() {
      let text = "请选择";
      switch (this.goods.reduce_stock_method) {
        case 0:
          text = "拍下减库存";
          break;
        case 1:
          text = "付款减库存";
          break;
        case 2:
          text = "永不减库存";
          break;
        default:
          break;
      }
      return text;
    }
  },
  methods: {
    tapTouch(id) {
      // console.log(id, this.radio);
      if (this.radio && this.radio == id) {
        return;
      } else {
        this.radio = id;
      }
    },
    delProject(index) {
      this.widgets.appointment_project.splice(index, 1);
    },
    async on_search() {
      this.getProjectInit();
      this.getProject();
    },
    getProjectInit() {
      this.page = 1;
      this.total_page = 0;
    },
    async getProject() {
      let json = {
        search: {},
        page: this.page
      };
      json.search.title = this.keyword;
      let { msg, data, result } = await $http.post("plugin.appointment.frontend.project.store-project-list", json, ".");
      if (!result) {
        this.$toast(msg);
        return;
      }
      this.projectList = data.data;
      this.total_page = data.last_page;
    },
    thumbUrlDel(e) {
      this.goods.thumb_url.splice(e, 1);
      console.log(e, this.goods.thumb_url);
    },
    imgUpload(e, key) {
      if (this.active == 1) {
        if (key == "thumb_url") {
          this.goods.thumb_url.push(e);
          return;
        }
        this.goods[key] = e;
      }
    },
    async submitTap() {
      let is_validate = await this.validate();
      if (!is_validate) return;
      let { data, msg, result } = await $http.post("plugin.appointment.frontend.project-goods.add-goods", is_validate, ".");
      console.log(data, msg, result);
      if (!result) return this.$toast(msg);
      this.$toast(msg);
      this.$router.go(-1);
    },
    validate() {
      if (this.fun.isTextEmpty(this.goods.title)) {
        this.$toast("请输入商品名称");
        return false;
      }
      if (this.fun.isTextEmpty(this.goods.sku)) {
        this.$toast("请输入商品单位");
        return false;
      }
      if (this.goods.category.length <= 0) {
        this.$toast("请选择商品分类");
        return false;
      }
      if (this.fun.isTextEmpty(this.goods.thumb)) {
        this.$toast("请上传商品图片");
        return false;
      }
      if (this.fun.isTextEmpty(this.goods.price)) {
        this.$toast("请输入商品现价");
        return false;
      }
      if (this.fun.isTextEmpty(this.goods.stock)) {
        this.$toast("请输入商品库存");
        return false;
      }
      let projectArr = this.widgets.appointment_project;
      let projectCheck = 4;
      if (projectArr.length <= 0) projectCheck = 1;
      for (let i = 0; i < projectArr.length; i++) {
        if (this.fun.isTextEmpty(projectArr[i].project_id)) {
          projectCheck = 2;
        } else if (this.fun.isTextEmpty(projectArr[i].service_count)) {
          projectCheck = 3;
        }
      }
      if (projectCheck == 1) {
        this.$toast("请添加项目信息");
        return false;
      } else if (projectCheck == 2) {
        this.$toast("请选择项目");
        return false;
      } else if (projectCheck == 3) {
        this.$toast(`请填写预约次数`);
        return false;
      }
      let json = {
        goods: { ...this.goods },
        widgets: { ...this.widgets }
      };
      if (!this.fun.isTextEmpty(this.goodsId)) {
        json.id = this.goodsId;
      }
      return json;
    },
    onClickLeft() {
      this.showSearchProject = false;
      this.page = 1;
      this.total_page = 0;
      this.showSearchProject_index = null;
      this.radio = "";
    },
    onClickRight() {
      this.showSearchProject = false;
      console.log(this.radio, this.showSearchProject_index);
      this.widgets.appointment_project[this.showSearchProject_index].project_id = this.radio;
    },
    async showSearchProjectOpen($event, ind) {
      this.radio = this.widgets.appointment_project[ind].project_id;
      this.getProjectInit();
      await this.getProject();
      this.showSearchProject = true;
      this.showSearchProject_index = ind;
    },
    addProjectMethod() {
      let obj = {
        service_count: "", //预约次数
        project_id: "", //选择的项目id
        price: "",
        worker_commission: "",
        merchant_staff_commission: "",
        area_set: 0,
        province: "",
        city: "",
        district: "",
        street: ""
      };
      // let arr = [];
      this.widgets.appointment_project.push(obj);
    },
    areaSwitchTap(e, val) {
      this.widgets.appointment_project[val].area_set = e;
    },
    switchTap(val) {
      this.goods.no_refund = val;
    },
    editStockType(event) {
      this.goods.reduce_stock_method = event;
    },
    showStockTypePop() {
      this.$refs.stockPopup.showPopup();
    },
    removeCategory(index) {
      this.goodsCategory.splice(index, 1);
      this.goods.category.splice(index, 1);
    },
    async getGoodsDetail() {
      await this.getProject();
      $http.get(this.getDatUrl, this.getJson, "loading").then(response => {
        let { category, title, sku, stock, thumb, thumb_url, content, market_price, price, cost_price, no_refund, goods_sn, product_sn, reduce_stock_method } = response.data;
        this.goods.category = category;
        this.goods.title = title;
        this.goods.sku = sku;
        this.goods.stock = stock;
        this.goods.thumb = thumb;
        this.goods.thumb_url = thumb_url;
        this.goods.content = content;
        this.goods.market_price = market_price;
        this.goods.price = price;
        this.goods.cost_price = cost_price;
        this.goods.no_refund = no_refund;
        this.goods.goods_sn = goods_sn;
        this.goods.product_sn = product_sn;
        this.goods.reduce_stock_method = reduce_stock_method;
        this.reversefilterCategory(category);
        this.widgets.appointment_project = response.data.has_many_appointment_goods;
      });
    },
    getClass() {
      $http.get("plugin.appointment.frontend.project-goods.get-category-list", {}, "loading").then(response => {
        if (response.result == 1) {
          this.categoryMenus = response.data;
        } else {
          this.$toast(response.msg);
        }
      });
    },
    editCategory(event) {
      let isRepeat = this.goodsCategory.some(item => {
        if (event.thirdid) {
          return item.parentid == event.parentid && item.childid == event.childid && item.thirdid == event.thirdid;
        } else {
          return item.parentid == event.parentid && item.childid == event.childid;
        }
      });
      if (isRepeat) {
        return this.$toast("不能重复添加商品分类");
      }
      if (this.addCategoryIndex !== undefined && this.addCategoryIndex !== "") {
        this.goodsCategory.splice(this.addCategoryIndex, 1, event);
      } else {
        this.goodsCategory.push(event);
      }
      this.goodsCategory.forEach((ele, ind) => {
        this.filterCategory(ele, ind);
      });
    },
    reversefilterCategory(array) {
      let arr = [];
      for (let i = 0; i < array.length; i++) {
        arr[i] = {};
        for (let j = 0; j < array[i].length; j++) {
          if (array[i][j].level == 1) {
            arr[i].parentid = array[i][j].id;
            arr[i].parent_name = array[i][j].name;
          } else if (array[i][j].level == 2) {
            arr[i].childid = array[i][j].id;
            arr[i].child_name = array[i][j].name;
          } else if (array[i].length == 3 && array[i][j].level == 3) {
            arr[i].thirdid = array[i][j].id;
            arr[i].third_name = array[i][j].name;
          }
        }
      }
      this.goodsCategory = arr;
      console.log(arr, "wwwwwwwwwwwwwww");
    },
    filterCategory(obj, ind) {
      let isObj = {};
      let arr = [];
      for (const key in obj) {
        if (key == "parentid") {
          isObj = {};
          isObj.id = obj[key];
          isObj.level = 1;
          arr[0] = isObj;
        } else if (key == "childid") {
          isObj = {};
          isObj.id = obj[key];
          isObj.level = 2;
          arr[1] = isObj;
        } else if (key == "thirdid") {
          isObj = {};
          isObj.id = obj[key];
          isObj.level = 3;
          arr[2] = isObj;
        }
      }
      this.goods.category[ind] = arr;
    },
    // 商品分类
    showCategoryPop(activeTag, index) {
      if (index !== undefined && index !== "") {
        this.addCategoryIndex = index;
      } else {
        this.addCategoryIndex = "";
      }
      this.$refs.categoryPopup.showPopup(activeTag);
    },
    saveGoodsDetail(event) {
      this.goods.content = event;
    },
    showGoodsDetailPop() {
      this.$refs.detailPopup.showPopup();
    }
  },
  components: {
    goodsDetailPopup,
    goodsCategoryPopup,
    stockTypePopup,
    cellGroup
  }
};
</script>
<style lang="scss" scoped>
.AppointmentAddGood {
  overflow: hidden;
  padding-bottom: 6rem;
  .searchBox {
    margin: 0 0.75rem;
    margin-top: 1rem;
    .van-search {
      padding: 0;
    }
    .cell {
      display: flex;
      justify-content: space-between;
      padding: 1rem 0;
      border-bottom: 1px solid #ececec;
    }
  }
  .subBox {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    .subBtn {
      margin: 1.97rem 0.75rem 1.25rem 0.75rem;
      padding: 0.78rem;
      box-sizing: border-box;
      font-weight: 500;
      font-size: 0.94rem;
      color: #ffffff;
      background: #f15353;
      border-radius: 1.88rem;
    }
  }
  .goodsBox {
    margin: 0.63rem 0.75rem;
  }
  .porject {
    margin: 0 0.75rem;
    margin-bottom: 1.56rem;
    overflow: hidden;
    .projectTemplate {
      padding-top: 1.16rem;
      .projectTemplate_t {
        display: flex;
        justify-content: space-between;
        margin-bottom: 0.66rem;
        .name {
          font-weight: bold;
          font-size: 0.94rem;
        }
        .del {
          font-size: 0.81rem;
          color: #6e6e79;
        }
      }
    }
    .addProject {
      margin: 0 auto;
      margin-top: 1.56rem;
      width: 9.94rem;
      height: 2.5rem;
      border-radius: 1.88rem;
      border: 0.03rem solid #f15353;
      font-size: 0.94rem;
      font-weight: 500;
      line-height: 2.5rem;
      text-align: center;
      color: #f15353;
    }
  }
}
.boxCell {
  background: #fff;
  .cellS {
    white-space: pre-wrap;
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
  }
  .category-tag {
    position: relative;
    display: inline-block;
    color: #9897a4;
    padding: 0.5rem;
    font-size: 0.625rem;

    .close-icon {
      position: absolute;
      right: 0;
      top: 0;
      font-size: 1rem;
    }
  }
}
</style>
